<script setup>
import { ref, onMounted } from 'vue'
import { mapDataInfo, layerList } from '@/utils/api.js'
import wlsLarge from '@/components/common/wls-large.vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute();
const router = useRouter();
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import XYZ from 'ol/source/XYZ.js';
import { defaults as defaultControls, FullScreen } from 'ol/control.js';
import Feature from 'ol/Feature.js';
import { Point } from 'ol/geom.js';
import { createStringXY } from 'ol/coordinate.js';
import { fromLonLat, transform, toLonLat } from 'ol/proj';
import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style.js';
import { Vector as VectorSource, Cluster } from 'ol/source.js';
import VectorSources from 'ol/source/Vector.js';
import { Tile as TileLayer, Vector as VectorLayer, Heatmap as HeatmapLayer } from 'ol/layer.js';
import ImageWMS from 'ol/source/ImageWMS';
import GeoJSON from 'ol/format/GeoJSON.js';
import Overlay from 'ol/Overlay.js';
import aniPng from '@/assets/images/ani_anchor_bottom_center.png'

const emit = defineEmits(['wgpup'])

let areaId = '';
const iswl = ref(false);
const wlm = ref([]);
let container = null;
let closer = null;
let PopOverlay = null;
let olmap = null;
let AllLayers = {};
const xyz = new TileLayer({
    source: new XYZ({
        url: 'https://t3.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f24cec70606332017dcd39a4fb60dd11'
    }),
});


const GSImageStyle = (feature) => {
    let src = feature.get('iconSrc');
    let anchor = [0, 1];
    //根据图标文件名 设置定位点  地图上放置的图标更改文件名即可保持一致
    if (src != '') {
        if (src.indexOf('anchor_bottom_center') != -1) {
            anchor = [0.5, 1];
        } else if (src.indexOf('anchor_bottom_left') != -1) {
            anchor = [0, 1];
        } else if (src.indexOf('anchor_bottom_right') != -1) {
            anchor = [1, 1];
        } else if (src.indexOf('anchor_center_center') != -1) {
            anchor = [0.5, 0.5];
        } else if (src.indexOf('anchor_top_center') != -1) {
            anchor = [0.5, 0];
        } else if (src.indexOf('anchor_top_left') != -1) {
            anchor = [0, 0];
        } else if (src.indexOf('anchor_top_right') != -1) {
            anchor = [1, 0];
        }
        return new Icon({
            src: feature.get('iconSrc'),
            anchor: anchor,
        });
    }
}

const styleFunction = (feature) => {
    if (feature.getGeometry().getType() == 'Point') {
        let Point = null;
        if (feature.get('fillColor').indexOf('#') != -1) {
            Point = new Style({
                image: new CircleStyle({
                    radius: feature.get("radius"),
                    fill: new Fill({
                        color: feature.get("fillColor")
                    }),
                    stroke: new Stroke({
                        color: feature.get("borderColor"),
                        width: 2
                    })
                }),
                text: new Text({
                    font: '14px Microsoft YaHei',
                    text: feature.get('text'),
                    fill: new Fill({
                        color: feature.get('textColor')
                    }),
                    offsetY: feature.get('offsetY'),
                    // 文字描边
                    // stroke: new Stroke({
                    //     color: 'white',
                    //     width: 0
                    // }),
                })
            })
        } else {
            Point = new Style({
                image: GSImageStyle(feature),
                text: new Text({
                    font: '14px Microsoft YaHei',
                    text: feature.get('text'),
                    fill: new Fill({
                        color: feature.get('textColor')
                    }),
                    offsetY: feature.get('offsetY'),
                    // stroke: new Stroke({
                    //     color: 'white',
                    //     width: 1
                    // }),
                })
            })
        }
        return [Point]
    }

    if (feature.getGeometry().getType() == 'Polygon' || feature.getGeometry().getType() == 'MultiPolygon') {
        let Polygon = new Style({
            stroke: new Stroke({
                color: feature.get('borderColor'),
                width: 1
            }),
            fill: new Fill({
                color: feature.get("fillColor")
            }),
            text: new Text({
                font: '14px Microsoft YaHei',
                text: feature.get('text'),
                fill: new Fill({
                    color: feature.get('textColor')
                }),
                // stroke: new Stroke({
                //     color: 'white',
                //     width: 0
                // }),
            })
        })
        return [Polygon]
    }

    if (feature.getGeometry().getType() == 'LineString') {
        let LineString = new Style({
            stroke: new Stroke({
                color: feature.get('borderColor'),
                width: 3
            }),
            text: new Text({
                font: '14px Microsoft YaHei',
                text: feature.get('text'),
                fill: new Fill({
                    color: feature.get('textColor')
                }),
                stroke: new Stroke({
                    color: 'white',
                    width: 1
                }),
            })
        })
        return [LineString]
    }
}

const addGeoJson = (data, id) => {
    if (typeof (AllLayers[id]) != "undefined") {
        olmap.removeLayer(AllLayers[id]);
        delete AllLayers[id];
    }
    let geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
            'type': 'name',
            'properties': {
                'name': 'EPSG:4326'
            }
        },
        'features': []
    };
    var MyVectorSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonObject),
    });

    AllLayers[id] = new VectorLayer({
        source: MyVectorSource,
        style: styleFunction
    });
    var MySource = AllLayers[id].getSource();
    data.forEach((e => {
        MySource.addFeatures(
            (new GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            })).readFeatures({
                "properties": {
                    "id": e.id,
                    "borderColor": e.borderColor,
                    "fillColor": e.fillColor,
                    "radius": e.radius,
                    "offsetY": e.offsetY,
                    "iconSrc": e.iconSrc,
                    "text": e.name,
                    "data": e.data,
                    "textColor": e.textColor,
                },
                'type': 'Feature',
                'geometry': e.geojson
            }))
    }));
    AllLayers[id].set("altitudeMode", "clampToGround");
    olmap.addLayer(AllLayers[id]);
    AllLayers[id].setZIndex(19);
}

const delLayers = (id) => {
    if (typeof (AllLayers[id]) != "undefined") {
        olmap.removeLayer(AllLayers[id]);
        delete AllLayers[id];
    }
}

const initmap = () => {
    container = document.getElementById('popup');
    closer = document.getElementById('popup-closer');
    PopOverlay = new Overlay({
        element: container,
        autoPan: {
            animation: {
                duration: 250,
            },
        },
    });
    olmap = new Map({
        target: 'map',
        controls: defaultControls({
            attribution: false,
            zoom: false,
            rotate: false
        }).extend([new FullScreen()]),
        layers: [xyz],
        overlays: [PopOverlay],
        view: new View({
            // center: fromLonLat([116.503720073467, 40.679310648968], 'EPSG:3857'),
            center: fromLonLat([128.66924999999998, 48.45055], 'EPSG:3857'),  // 翠北
            zoom: 11,
            maxZoom: 16
        }),
    });


    olmap.on('singleclick', function (evt) {
        let feature = olmap.forEachFeatureAtPixel(evt.pixel,
            function (feature) {
                return feature;
            });

        if (feature != undefined && feature) {

            if (feature.get('features') != undefined) {
                let data = {
                    type: '点位',
                    gridNumber: feature.get('features')[0].values_.properties.cameraEnvirId
                }
                emit('wgpup', data);
            }

            if (feature.get('data') != undefined) {
                let data = feature.get('data');
                emit('wgpup', data);
            }
        }
    });
}

const addHeatMap = (uniqueId, fenbu) => {
    //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
    if (typeof (AllLayers[uniqueId]) != "undefined") {
        olmap.removeLayer(AllLayers[uniqueId]);
        delete AllLayers[uniqueId];
    }
    /**geojson数据 绘制热力图**/
    let geojsonObject = {
        'type': 'FeatureCollection',
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        'features': []
    };
    for (var i = 0; i < fenbu.length; i++) {
        //console.log($scope.oneData.fenbu[i])
        var feature = {
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': transform(fenbu[i], 'EPSG:4326', 'EPSG:3857')
            }
        };
        console.log();
        geojsonObject.features.push(feature);
    }

    AllLayers[uniqueId] = new HeatmapLayer({
        source: new VectorSources({
            features: (new GeoJSON()).readFeatures(geojsonObject)
        }),
        blur: parseInt(10, 10),
        radius: parseInt(5, 10)
    });
    olmap.addLayer(AllLayers[uniqueId]);
}

const addcluster = (data, id) => {
    let sources = new VectorSource();
    for (var i = 1; i < data.length; i++) {
        var coordinates = transform([data[i].lon, data[i].lat], 'EPSG:4326', 'EPSG:3857');
        var feature = new Feature({
            geometry: new Point(coordinates),
            properties: {
                'cameraEnvirId': data[i].cameraEnvirId
            }
        });
        // feature.set('cameraEnvirId', data[i].cameraEnvirId);
        sources.addFeature(feature);
    }
    // 聚合
    let cluster = new Cluster({
        source: sources,
        distance: 100
    })

    AllLayers[id] = new VectorLayer({
        source: cluster,
        style: function (feature, resolution) {
            var size = feature.get('features').length;
            if (size == 1) {
                // aniPng
                return new Style({
                    image: new Icon({
                        src: aniPng,
                        anchor: [0.5, 1],
                    })
                })
            }
            else {
                return new Style({
                    image: new CircleStyle({
                        radius: 30,
                        stroke: new Stroke({
                            color: 'white'
                        }),
                        fill: new Fill({
                            color: '#01C144'
                        })
                    }),
                    text: new Text({
                        text: size.toString(),
                        fill: new Fill({
                            color: 'white'
                        })
                    })
                })
            }
        }
    })

    olmap.addLayer(AllLayers[id]);
    AllLayers[id].setZIndex(10);

}

const openLarge = (data) => {
    if (data != null) {
        wlm.value = data;
        iswl.value = true;
    }


};


onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
})

defineExpose({ initmap, addGeoJson, delLayers, addHeatMap, addcluster })

</script>
<template>
    <div id="map"></div>
    <wls-large :msg="wlm" v-if="iswl" @closeLarge="iswl = false" />
</template>
<style scoped>
#map {
    width: 100%;
    height: 100%;
    position: relative;
}

.My-marker {
    width: .5rem;
    height: 0.7rem;
    color: #fff;
    padding-top: 0.15rem;
    display: flex;
    /* align-items: center; */
    justify-content: center;
    background-image: url("/src/assets/images/mark.png");
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
    overflow: hidden;
}


.map-menu {
    display: flex;
    align-items: center;
    position: absolute;
    top: 16px;
    left: 16px;
    z-index: 22;
    /* overflow: hidden; */
    cursor: pointer;
}

.map-menu>div {
    width: 40px;
    height: 40px;
    margin-left: 16px;
    position: relative;
}

.map-menu>div img {
    width: 100%;
    height: 100%;
}

.mm-layers {
    padding: 20px 0 20px 20px;
    background-color: #FFFFFF;
    border-radius: 4px;
    position: absolute;
    top: 52px;
    left: 0;
    z-index: 2;
    /* overflow: hidden; */
}

.mm-layers::before {
    content: "";
    position: absolute;
    top: -10px;
    left: 20px;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 12px solid transparent;
    border-right: 12px solid transparent;
    border-bottom: 12px solid #FFFFFF;
}
</style>

<style>
.wls-mouse-position {
    position: absolute;
    bottom: 16px;
    left: 16px;
    font-size: 0.18rem;
    color: #fff;
}


.ol-popup {
    width: 4.5rem;
    /* height: 4.6rem; */
    padding: 0 .16rem;
    position: absolute;
    bottom: 12px;
    left: -50px;
    background-color: white;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
}

.ol-popup:after,
.ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}

.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}

.popup-title {
    width: 100%;
    height: .56rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.popup-title>div {
    height: 100%;
    display: flex;
    align-items: center;
}

.popup-title>div span {
    margin-left: 8px;
    font-size: .16rem;
}

.popup-img {
    width: 100%;
    height: 3rem;
}


.popup-img img {
    width: 100%;
    height: 100%;
}

.popup-img video {
    width: 100%;
    /* height: 100%; */
}

.popup-list-item {
    width: 100%;
    padding: 0.16rem 0;
    display: flex;
    align-items: center;
    color: #606266;
    border-bottom: 1px solid #DCDFE6;
    overflow: hidden;
}

.popup-list-span {
    display: inline-block;
    margin-left: 0.08rem;
    line-height: 2;
    white-space: nowrap;
    /* 禁止换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
    text-overflow: ellipsis;
    /* 超出部分显示省略号 */
}

.popup-list-s {
    width: 1px;
    height: 0.18rem;
    margin: 0 .24rem;
    background-color: #DCDFE6;
}

.popupc {
    font-size: 0.16rem;
    color: var(--wls-color);
    text-decoration: underline;
    cursor: pointer;
}
</style>